#!/bin/bash
# This script searches for ceph OSD devices and mounts them according to OSD id.

ceph_root="/osd"
ceph_tmp="$ceph_root/tmp"
cluster="ceph"


# trap EXIT function to remove any temporary mount or directory
declare tmpdir
function finish()
{
    if [[ -n "$tmpdir" ]]; then
        umount "$tmpdir" &>/dev/null
        rmdir "$tmpdir"
    fi
}
trap finish EXIT


# Trim leading or trailing whitespace
function trim()
{
    local var="$*"
    var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters
    var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
    echo -n "$var"
}

# Search for OSD's
function find_osds()
{
    local osds
    declare -a dev_list
    mapfile dev_list < <(lsblk -l -n -o NAME --exclude 1,7,11) # note -I not available in all versions of lsblk, use exclude instead
    for dev in "${dev_list[@]}"; do
        dev=/dev/$(trim "$dev")
        if blkid -p "$dev" | fgrep -q '4fbd7e29-9d25-41b8-afd0-062c0ceff05d'; then
            osds+=($dev)
        fi
    done
    echo "${osds[@]}"
}

# Get filesystem type - xfs,btrfs,ext4 etc
function get_fstype()
{
    blkid -o value -s TYPE "$dev"
}

# Get default mount options for osd
function get_mount_options()
{
    case "$1" in
        xfs) echo "rw,noatime,inode64"
        ;;
        *) echo "rw,noatime"
    esac
}

# Make the top level $ceph_tmp
mkdir -p $ceph_tmp

# Find osd's & mount them according to id
for dev in $(find_osds); do
    if ! grep -qs "$dev" /proc/mounts; then

        # Temporarily mount the OSD and read it's id
        tmpdir=$(mktemp -d --tmpdir="$ceph_tmp")
        [[ -d "$tmpdir" ]] && mount "$dev" "$tmpdir" &>/dev/null && {

            whoami="$tmpdir/whoami"
            if [[ -f "$whoami" ]]; then
                # Get OSD id
                id=$(cat "$whoami")
                umount "$dev" && rmdir "$tmpdir" && unset tmpdir

                # Get mount options depending on fs type and mount it
                type=$(get_fstype "$dev")
                options=$(get_mount_options "$type")

                mount_point="$ceph_root/$cluster-$id"
                # Create mount-point, then mount it
                mkdir -p "$mount_point"

                echo -n "Mounting $dev to $mount_point"
                mount -t "$type" -o "$options" "$dev" "$mount_point" && echo " : success" || " : failed"
            else
                umount "$dev" && rmdir "$tmpdir" && unset tmpdir
            fi
        }
    fi
done
